<?php

namespace App\Livewire;

use App\Models\ConnectionsTypesModel;
use App\Models\ServerModel;
use App\Models\SessionsModel;
use Livewire\Component;
use Services\Commands\CommandService;
use Services\Constants\SessionsConstants;

class SendCommandForm extends Component
{
    public $connection;

    public $ip;

    public $command;

    public function mount($connection, $ip)
    {
        $this->connection = $connection;
        $this->ip = $ip;
    }

    public function rules(): array
    {
        return [
            'command' => ['required', 'string'],
            'connection' => ['required', 'string', 'exists:connections_types,connection'],
            'ip' => ['required', 'ip', 'exists:servers,ip_address'],
        ];
    }

    public function send()
    {
        $this->validate();
        $server = ServerModel::query()->where(['ip_address' => $this->ip])->first();
        $connection = ConnectionsTypesModel::query()->where(['connection' => $this->connection])->first();
        $session = SessionsModel::query()
            ->where([
                ['user_id', '=', auth()->user()->id],
                ['server', '=', $this->ip],
                ['connection_id', '=', $connection->id],
                ['active', '=', true],
            ])
            ->first();
        app(CommandService::class)->interact(
            auth()->user()->id,
            $this->connection,
            SessionsConstants::DEFAULT_SESSION,
            $this->command,
            ['port' => $server->port,
                'host' => $server->ip_address,
                'properties' => json_decode($session->parameters, true),
            ],
            'interact');
    }

    public function render()
    {
        return view('livewire.server.send-command-form', ['connection' => $this->connection, 'ip' => $this->ip]);
    }
}
